package com.jiancong.controller;

import com.jiancong.domain.ResponseResult;
import com.jiancong.domain.entity.Menu;
import com.jiancong.domain.vo.MenuTreeVo;
import com.jiancong.domain.vo.RoleMenuTreeResponse;
import com.jiancong.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单权限表(Menu)控制层
 *
 * @author makejava
 * @since 2024-05-08 19:07:11
 */
@RestController
@RequestMapping("/system/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public ResponseResult getMenuList(@RequestParam(value = "menuName", required = false) String menuName,
                                      @RequestParam(value = "status", required = false) String status) {
        List<Menu> menus = menuService.getMenuList(menuName,status);
        return ResponseResult.okResult(menus);
    }

    @PostMapping
    public ResponseResult addMenu(@RequestBody Menu menu) {
        return menuService.insertMenu(menu);
    }

    // 获取菜单详情
    @GetMapping("{id}")
    public ResponseResult getMenuById(@PathVariable Long id) {
        Menu menu = menuService.selectMenuById(id);
        if (menu != null) {
            return ResponseResult.okResult(menu);
        } else {
            return ResponseResult.errorResult(404, "菜单不存在");
        }
    }

    // 更新菜单信息
    @PutMapping
    public ResponseResult updateMenu(@RequestBody Menu menu) {
        if (menuService.isSelfParent(menu)) {
            return ResponseResult.errorResult(400, "不能将父菜单设置为当前菜单");
        }
        boolean updated = menuService.updateMenu(menu);
        if (updated) {
            return ResponseResult.okResult();
        } else {
            return ResponseResult.errorResult(500, "菜单更新失败");
        }
    }

    @GetMapping("/treeselect")
    public ResponseResult selectTreeselect(){
        List<MenuTreeVo> menus = menuService.selectTreeselect();
        return ResponseResult.okResult(menus);
    }

    @GetMapping("/roleMenuTreeselect/{id}")
    public ResponseResult getRoleMenuTree(@PathVariable Long id) {
        RoleMenuTreeResponse roleMenuTreeResponse = menuService.getRoleMenuTreeAndPermissions(id);
        return ResponseResult.okResult(roleMenuTreeResponse);
    }
}